import { MouseEventHandler, useCallback } from "react";
import NextLink, { LinkProps } from "next/link";
import useRouterTo from "@/hooks/routeTo";
import { BaseChildrenProps } from "@/types/baseProps";
import { PagePath } from "@/app/(dashboard)/common/config/path";
type ReturnType = void | boolean;
interface MyLinkProps extends BaseChildrenProps {
  /**要跳转的路径，枚举值 */
  href: PagePath;
  /**跳转前要做的事，返回false将会阻止跳转（在判断成功前 */
  beforeJump?: () => Promise<ReturnType> | ReturnType;
  /**NextLink组件的其它参数 */
  otherProps?: Omit<LinkProps, "onClick" | "href">;
}
/**二次封装NextLink组件，支持预加载、阻止默认跳转行为，改为自制的路由加载(有进度条和鉴权)。 */
export default function MyLink({ href, children, className, style, beforeJump, otherProps }: MyLinkProps) {
  const { routerTo, showProgress, hideProgress } = useRouterTo();
  const to: MouseEventHandler<HTMLAnchorElement> = async (e) => {
    e.preventDefault();
    if (beforeJump) {
      showProgress();
      if ((await beforeJump()) === false) {
        console.log("阻止了");
        hideProgress();
        return;
      }
    }
    routerTo(href);
  };
  return (
    <NextLink href={href} onClick={to} className={className} style={style} {...otherProps}>
      {children}
    </NextLink>
  );
}
